<template>
  <div class="upload-container">
    <!-- 文件上传组件 -->
    <el-upload
      action="/system/oss/upload"
      :headers="headers"
      :show-file-list="true"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :on-error="handleError"
      :file-list="fileList"
      accept="*"  <!-- 允许所有文件类型 -->
    >
      <el-button size="mini" type="primary">
        <i class="el-icon-upload"></i> 点击上传（最大1024MB）
      </el-button>
    </el-upload>

    <!-- 上传成功后显示URL -->
    <el-table v-if="fileList.length > 0" :data="fileList" border style="margin-top: 15px;">
      <el-table-column prop="name" label="文件名" width="300"></el-table-column>
      <el-table-column prop="url" label="文件URL">
        <template slot-scope="scope">
          <a :href="scope.row.url" target="_blank">{{ scope.row.url }}</a>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";

export default {
  data() {
    return {
      headers: {
        Authorization: "Bearer " + getToken() // 携带Token认证
      },
      fileList: [] // 存储上传成功的文件信息
    };
  },
  methods: {
    // 上传前校验（与后端保持一致的1024MB限制）
    beforeUpload(file) {
      const maxSize = 1024 * 1024 * 1024; // 1024MB = 1073741824 bytes
      if (file.size > maxSize) {
        this.$message.error("文件大小不能超过1024MB");
        return false; // 阻止上传
      }
      return true;
    },

    // 上传成功回调
    handleSuccess(response, file) {
      if (response.code === 200) {
        this.fileList.push({
          name: file.name,
          url: response.url
        });
        this.$message.success("上传成功");
      } else {
        this.$message.error(response.msg || "上传失败");
      }
    },

    // 上传失败回调
    handleError(error) {
      this.$message.error("上传失败：" + (error.msg || "网络错误"));
    }
  }
};
</script>
